﻿using AgileConfig.Client.RegisterCenter;
using Ocelot.Configuration;
using Ocelot.DependencyInjection;
using Ocelot.Provider.Nacos;
using Ocelot.ServiceDiscovery;
using Ocelot.ServiceDiscovery.Providers;

namespace Service.Gateway.Core.AgileConfigServiceDiscovery
{
    /// <summary>
    /// 
    /// </summary>
    public static class AgileConfigProviderFactory
    {
        public static ServiceDiscoveryFinderDelegate Get = delegate (IServiceProvider provider, ServiceProviderConfiguration config, DownstreamRoute route)
        {
            IDiscoveryService service = provider.GetService<IDiscoveryService>();
            if (config.Type?.ToLower() == "agilegonfig" && service != null)
            {
                return new AgileConfigServiceDiscoveryProvider(service, route);
            }
            return (IServiceDiscoveryProvider)null;
        };


        /// <summary>
        /// 
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="section"></param>
        /// <returns></returns>
        public static IOcelotBuilder AddAgileConfigDiscovery(this IOcelotBuilder builder, string section = "agilegonfig")
        {

            builder.Services.AddSingleton(AgileConfigProviderFactory.Get);
            builder.Services.AddSingleton(AgileConfigurationProvider.Get);
            return builder;
        }
    }

}
